import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Row,
  Space,
  Image
} from 'antd';
import JsBarcode from "jsbarcode";
import { useState } from 'react';


import commonService from '@/api/services/commonService';

export default function PickerPage() {

  const [id, setId] = useState(false);
  const [info, setInfo] = useState<any>({});

  const [form] = Form.useForm();

  const handleChange = (e: any) => {
    const val = e.target.value;
    setId(val);
    getInfo(val);
  };

  const getInfo = (val?: any) => {
    commonService.getCustomApi('/admin/order-detail/viewOrderDetail', { orderDetailId: val || id }).then((res) => {
      setInfo(res);
      form.resetFields();
    });
  };

  const toPrint = () => {
    const { id, size, num } = info;
    const barcodeOptions = {
      format: "CODE128", // 条形码格式
      lineColor: "#000000", // 条形码线颜色
      width: 2, // 条形码线宽度
      height: 50 // 条形码高度
    };

    // 创建一个新的canvas元素
    const canvas = document.createElement('canvas');
    JsBarcode(canvas, `${id}-${size}`, barcodeOptions);

    // 将canvas转换为图像
    const barcodeImage = canvas.toDataURL("image/png");

    // 创建一个新的窗口并打印条形码
    const printWindow: any = window.open('', '_blank');
    let html = `<html><head><title>Print</title></head><body>`;
    for (let i = 0; i < num; i++) {
      console.log(i, '===>11111');
      html += `<img src="${barcodeImage}" alt="Barcode" /><br>`;
    }
    html += `</body></html>`;
    printWindow.document.write(html);
    printWindow.document.close();

    printWindow.onload = function () {
      printWindow.print();
      printWindow.close();
    };
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card>
      <Form form={form} >
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="扫描条码" name="orderNumber" className="!mb-0">
                <Input autoFocus onChange={handleChange} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      {info.id ? <Card
        title='质检转码'
        extra={
          <div className="flex flex-row gap-[10px]">
            <Button
              type="primary"
              onClick={toPrint}
            >
              打印
            </Button>
          </div>
        }
      >
        <div className='flex flex-col gap-[10px]'>
          <div>ID：{info.id}-{info.size}</div>
          <div>订单号：{info.orderNumber}</div>
          <div>标题：{info.title}</div>
          <div>缩略图：
            {JSON.parse(info.thumbnail)?.map((item: any, index: number) => {
              return <Image className='!w-[120px]' src={item} alt="img" key={index} />;
            })}
          </div>
          <div>颜色：{info.color}</div>
          <div>数量：{info.num}</div>
        </div>

      </Card> : ''}
    </Space>
  );
}
